import AsyncStorage from '@react-native-async-storage/async-storage';

const API_BASE_URL = 'http://192.168.75.127:3000/api';

// 获取token
export const getAccessToken = async () => await AsyncStorage.getItem('accessToken');
export const getRefreshToken = async () => await AsyncStorage.getItem('refreshToken');

// 保存token
export const saveTokens = async (accessToken: string, refreshToken: string) => {
  if (accessToken !== undefined && accessToken !== null) {
    await AsyncStorage.setItem('accessToken', accessToken);
  } else {
    await AsyncStorage.removeItem('accessToken');
  }
  if (refreshToken !== undefined && refreshToken !== null) {
    await AsyncStorage.setItem('refreshToken', refreshToken);
  } else {
    await AsyncStorage.removeItem('refreshToken');
  }
};

// 清除token
export const clearTokens = async () => {
  await AsyncStorage.removeItem('accessToken');
  await AsyncStorage.removeItem('refreshToken');
};

// 自动带token的fetch
export const authRequest = async (url: string, options: any = {}) => {
  let accessToken = await getAccessToken();
  let refreshToken = await getRefreshToken();
  if (!options.headers) options.headers = {};
  if (accessToken) {
    options.headers['Authorization'] = `Bearer ${accessToken}`;
  }
  let res = await fetch(API_BASE_URL + url, options);
  if (res.status === 401 && refreshToken) {
    // accessToken失效，尝试用refreshToken换新
    const refreshRes = await fetch(API_BASE_URL + '/auth/refresh-token', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ refreshToken })
    });
    if (refreshRes.ok) {
      const { accessToken: newAccessToken } = await refreshRes.json();
      if (newAccessToken !== undefined && newAccessToken !== null) {
        await AsyncStorage.setItem('accessToken', newAccessToken);
      } else {
        await AsyncStorage.removeItem('accessToken');
      }
      options.headers['Authorization'] = `Bearer ${newAccessToken}`;
      // 重试原请求
      res = await fetch(API_BASE_URL + url, options);
    } else {
      // refreshToken也失效，清除token
      await clearTokens();
    }
  }
  return res;
}; 